<template>
	<view class="container">
		<!-- 订单信息 -->
		<view class="order-info">
			<view class="info-row">
				<text class="label">充值金额：</text>
				<input 
					class="amount-input" 
					type="digit"
					v-model="rechargeAmount" 
					placeholder="请输入充值金额"
					:disabled="this.type == '1'"
					@input="handleAmountInput"
				/>
			</view>
		</view>
		<!-- 充后余额 -->
		<view class="order-info" v-if="this.type == ''">
			<view class="info-row">
				<text class="label">充后余额：</text>
				<text class="value">{{ afterBalance }}</text>
			</view>
		</view>
		<!-- 转账账户 -->
		<view class="transfer-accounts" v-if="this.type == ''">
			<text class="transfer-accounts-title">转账账户</text>
			<view 
				class="account-item" 
				v-for="(account, index) in transferAccounts" 
				:key="index"
				@click="copyAccount(account)"
			>
				<view class="account-content">
					<text class="account-label">{{ account.dictLabel }}：</text>
					<text class="account-value">{{ account.dictValue }}</text>
				</view>
				<text class="copy-icon">复制</text>
			</view>
		</view>
		<!-- 转账记录上传 -->
		<view class="transfer-record-upload">
			<view class="transfer-record-upload-title">{{ this.type == '' ? '充值凭证上传' : '充值凭证' }}<text style="color: #ff4069;">*</text></view>
			<js-uploadfile v-model="image.dataMap" :biz-key="image.id" biz-type="recharge_image"></js-uploadfile>
		</view>
		
		<!-- 备注 -->
		<view class="remarks-section">
			<view class="remarks-header">
				<text class="remarks-label">备注</text>
				<text class="remarks-limit">限30字</text>
			</view>
			<textarea 
				class="remarks-input" 
				v-model="remarks" 
				placeholder="请填写备注信息"
				maxlength="30"
			></textarea>
		</view>
		
		<!-- 提交按钮 -->
		<view class="submit-container">
			<view class="submit-btn" v-if="this.type == ''" @click="submitWalletRecharge">
				<text class="submit-text">提交充值申请</text>
			</view>
			<view v-if="this.type == '1'" style="display: flex; gap: 10px;">
				<view class="submit-btn reject-btn" @click="rejectRecharge">
					<text class="submit-text">审核拒绝</text>
				</view>
				<view class="submit-btn approve-btn" @click="submitAllPayment">
					<text class="submit-text">审核通过</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			type: '', // 类型：'1'=审核场景
			title: '', // 页面标题
			remarks: '',
			rechargeAmount: '', // 充值金额
			currentBalance: 0, // 当前余额
			rechargeRecordId: '', // 充值记录ID（审核时使用）
			orderData: {}, // 订单数据（订单补交场景使用）
			orderNo: '', // 订单号
			orderId: '', // 订单ID
			image: {
				dataMap: {
					recharge_image: '',
					recharge_image__del: ''
				},
				id: ''
			},
			transferAccounts: [] // 转账账户列表
		}
	},
	computed: {
		// 充后余额
		afterBalance() {
			if (this.type == '') {
				const amount = parseFloat(this.rechargeAmount || 0)
				return (parseFloat(this.currentBalance || 0) + amount).toFixed(2)
			}
			return '0.00'
		}
	},
	onLoad(options) {
		if(options.type) {
			this.type = options.type
		}
		if(options.title) {
			this.title = options.title
			uni.setNavigationBarTitle({
				title: this.title
			})
		}
		
		// 判断是否为钱包充值（没有订单信息）
		if (!options.recharge) {
			// 钱包充值场景
			// 加载当前余额
			this.loadBalance()
			// 加载转账账户
			this.loadTransferAccounts()
		} else {
			// 审核场景
			let order = JSON.parse(options.recharge)
			this.orderData = order
			this.rechargeAmount = order.amount
			this.remarks = order.remark
			this.rechargeRecordId = order.id
			this.image.id = order.id
		}
	},
	methods: {
		// 处理金额输入
		handleAmountInput(e) {
			let value = e.detail.value
			// 移除非数字和小数点的字符
			value = value.replace(/[^\d.]/g, '')
			// 确保只有一个小数点
			const parts = value.split('.')
			if (parts.length > 2) {
				value = parts[0] + '.' + parts.slice(1).join('')
			}
			// 限制小数点后两位
			if (parts.length === 2 && parts[1].length > 2) {
				value = parts[0] + '.' + parts[1].substring(0, 2)
			}
			this.rechargeAmount = value
		},
		// 加载当前余额
		loadBalance() {
			this.$u.api.wallet.getBalance().then(res => {
				if (res && res.result == 'true' && res.data) {
					this.currentBalance = parseFloat(res.data.balance || 0)
				}
			}).catch(err => {
				console.error('获取余额失败:', err)
			})
		},
		// 加载转账账户
		loadTransferAccounts() {
			this.$u.api.mainType.treeData({dictType: 'petty_cash'}).then(res => {
				if (res && Array.isArray(res) && res.length > 0) {
					// 去掉最后一个
					this.transferAccounts = res.slice(0, -1)
				} else {
					this.transferAccounts = []
				}
			}).catch(err => {
				console.error('获取转账账户失败:', err)
				this.transferAccounts = []
			})
		},
		// 复制账户信息
		copyAccount(account) {
			const copyText = `${account.dictValue}`
			uni.setClipboardData({
				data: copyText,
				success: () => {
					uni.showToast({
						title: '已复制',
						icon: 'success',
						duration: 1500
					})
				},
				fail: () => {
					uni.showToast({
						title: '复制失败',
						icon: 'none'
					})
				}
			})
		},
		// 提交钱包充值
		submitWalletRecharge() {
			// 验证充值金额
			const amount = parseFloat(this.rechargeAmount || 0)
			if (!this.rechargeAmount || amount <= 0) {
				uni.showToast({
					title: '请输入充值金额，必须大于0',
					icon: 'none'
				})
				return
			}

			if (!this.image.dataMap.recharge_image) {
				uni.showToast({
					title: '请上传充值凭证',
					icon: 'none'
				})
				return
			}

			uni.showModal({
				title: '提示',
				content: '确定提交该充值申请吗？',
				success: (res) => {
					if (res.confirm) {
						this.submitRecharge()
					}
				}
			})
		},
		//提交申请
		submitRecharge() {
			// 构建请求参数
			const params = {
				amount: this.rechargeAmount,
				remark: this.remarks || ''
			}
			
			// 添加图片相关参数
			if (this.image.dataMap.recharge_image) {
				params['dataMap[recharge_image]'] = this.image.dataMap.recharge_image
			}
			if (this.image.dataMap.recharge_image__del) {
				params['dataMap[recharge_image__del]'] = this.image.dataMap.recharge_image__del
			}
			
			console.log('提交充值参数:', params)
			
			uni.showLoading({
				title: '提交中...',
				mask: true
			})
			
			// 调用钱包充值接口
			this.$u.api.wallet.recharge(params).then(res => {
				uni.hideLoading()
				
				if (res && res.result == 'true') {
					uni.showToast({
						title: res.message || '充值申请提交成功，等待审核',
						icon: 'success'
					})
					
					// 延迟返回
					setTimeout(() => {
						uni.navigateBack()
					}, 1000)
				} else {
					uni.showToast({
						title: res.message || '充值申请提交失败',
						icon: 'none'
					})
				}
			}).catch(err => {
				uni.hideLoading()
				console.error('充值申请提交失败:', err)
				uni.showToast({
					title: '提交失败，请重试',
					icon: 'none'
				})
			})
		},
		// 审核通过
		submitAllPayment() {
			const title = '确定审核通过该充值申请吗？'
			uni.showModal({
				title: '提示',
				content: title,
				success: (res) => {
					if (res.confirm) {
						this.approvePayment('1')
					}
				}
			})
		},
		// 审核拒绝
		rejectRecharge() {
			uni.showModal({
				title: '提示',
				content: '确定拒绝该充值申请吗？',
				success: (res) => {
					if (res.confirm) {
						this.approvePayment('2')
					}
				}
			})
		},
		// 调用审核接口
		approvePayment(auditResult) {
			uni.showLoading({
				title: '审核中...',
				mask: true
			})
			
			if (!this.rechargeRecordId) {
				uni.hideLoading()
				uni.showToast({
					title: '充值记录ID不存在',
					icon: 'none'
				})
				return
			}
			
			const params = {
				id: this.rechargeRecordId,
				auditResult: auditResult
			}
			
			// 添加审核备注（可选）
			if (this.remarks) {
				params.auditRemark = this.remarks
			}
			
			this.$u.api.wallet.audit(params).then(res => {
				uni.hideLoading()
				
				if (res && res.result == 'true') {
					uni.showToast({
						title: res.message || '审核成功',
						icon: 'success'
					})
					
					// 延迟返回
					setTimeout(() => {
						uni.navigateBack()
					}, 1000)
				} else {
					uni.showToast({
						title: res.message || '审核失败',
						icon: 'none'
					})
				}
			}).catch(err => {
				uni.hideLoading()
				console.error('充值审核失败:', err)
				uni.showToast({
					title: '审核失败，请重试',
					icon: 'none'
				})
			})
		}
	}
}
</script>

<style scoped>
.container {
	background-color: #f5f5f5;
	padding-bottom: 100px;
}

/* 订单信息 */
.order-info {
	background-color: #ffffff;
	padding: 20px;
	margin-bottom: 10px;
}

.info-row {
	display: flex;
	align-items: center;
	margin-bottom: 10px;
}

.info-row:last-child {
	margin-bottom: 0;
}

.label {
	font-size: 14px;
	color: #666666;
	min-width: 80px;
}

.value {
	font-size: 14px;
	color: #333333;
	flex: 1;
}

.amount-input {
	flex: 1;
	height: 40px;
	padding: 0 15px;
	border: 1px solid #f0f0f0;
	border-radius: 8px;
	font-size: 14px;
	color: #333333;
	background-color: #fafafa;
	box-sizing: border-box;
}

.amount-input:disabled {
	background-color: #f5f5f5;
	color: #999999;
}

/* 转账账户 */
.transfer-accounts {
	background-color: #ffffff;
	padding: 20px;
	margin-bottom: 10px;
}

.transfer-accounts-title {
	font-size: 16px;
	color: #333333;
	font-weight: bold;
	margin-bottom: 15px;
	display: block;
}

.account-item {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 10px 0;
	border-bottom: 1px solid #f8f8f8;
}

.account-item:active {
	background-color: #f5f5f5;
}

.account-item:last-child {
	border-bottom: none;
}

.account-content {
	display: flex;
	align-items: center;
	flex: 1;
}

.account-label {
	font-size: 14px;
	color: #666666;
}

.account-value {
	font-size: 14px;
	color: #333333;
	font-weight: 500;
}

.copy-icon {
	font-size: 12px;
	margin-left: 10px;
	opacity: 0.6;
	background-color: #f0f0f0;
	padding: 4px 8px;
	border-radius: 4px;
}

/* 转账记录上传 */
.transfer-record-upload {
	background-color: #ffffff;
	padding: 20px;
	margin-bottom: 10px;
}

.transfer-record-upload-title {
	font-size: 16px;
	color: #333333;
	margin-bottom: 15px;
	font-weight: bold;
}

/* 备注 */
.remarks-section {
	background-color: #ffffff;
	padding: 20px;
	margin-bottom: 10px;
}

.remarks-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 15px;
}

.remarks-label {
	font-size: 16px;
	color: #333333;
	font-weight: bold;
}

.remarks-limit {
	font-size: 14px;
	color: #999999;
}

.remarks-input {
	width: 100%;
	max-height: 70px;
	padding: 15px;
	border: 1px solid #f0f0f0;
	border-radius: 8px;
	font-size: 14px;
	color: #333333;
	background-color: #fafafa;
	box-sizing: border-box;
}

/* 提交按钮 */
.submit-container {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background-color: #ffffff;
	padding: 15px 20px;
	border-top: 1px solid #f0f0f0;
}

.submit-btn {
	height: 45px;
	background-color: #ff4069;
	border-radius: 25px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.submit-text {
	font-size: 16px;
	color: #ffffff;
	font-weight: bold;
}

.reject-btn {
	background-color: #ff4069;
	flex: 1;
}

.approve-btn {
	background-color: #19be6b;
	flex: 1;
}
</style>

